package com.sendpo.zjx.sendpo.fragment.helpingorder;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableRecyclerView;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.activity.ModifyPayPassActivity;

import com.sendpo.zjx.sendpo.domain.HelpInfoDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.MD5Util;
import com.sendpo.zjx.sendpo.utils.OrderInfoUtil2_0;
import com.sendpo.zjx.sendpo.utils.PayDomain;
import com.sendpo.zjx.sendpo.utils.PayResult;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2017/8/21.
 */

public class MyselHelpOrder1Fragment extends BaseMyselfHelpOrderSingleFragment {


    View rootView = null;
    @BindView(R.id.recyclerview)
    PullableRecyclerView recyclerview;
    @BindView(R.id.pulltofresh)
    public PullToRefreshLayout pulltofresh;

    private LinearLayoutManager lm;

    public Dialog paydialog;
    private RadioGroup radioGroup;

    private RecylcerAdaper adpter;
    private int pagenow=1;
    public int currentlastitem=0;
    public boolean lastloading=false;

    public boolean isFirstPay=true;
    public  boolean ispayLoding=false;


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HttpUrl.SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Gson gson=new Gson();
                        PayDomain pay=gson.fromJson(payResult.getResult(),PayDomain.class);
                         Bundle bundle=msg.getData();
                        String orderId=bundle.getString("orderId");
                        String touserId=bundle.getString("touserId");
                        String money=bundle.getString("money");
                        int position=bundle.getInt("position");
                        payfor(orderId,touserId,money,position);
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        System.out.println("***************"+payResult.getResult());
                    //    Toast.makeText(mActivity.getApplicationContext(), "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(mActivity.getApplicationContext(), "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        };
    };




    @Override
    public View initView() {
        View view = View.inflate(mActivity, R.layout.fragment_helpingorder_recycler, null);
        ButterKnife.bind(view, mActivity);
        return view;
    }


    public void initData() {
        lm = new LinearLayoutManager(mActivity, OrientationHelper.VERTICAL, false);
        recyclerview.setLayoutManager(lm);
        List<HelpInfoDomain.DataBean> dataBeanList=new ArrayList<>();
        recyclerview.setAdapter(adpter=new RecylcerAdaper(dataBeanList,mActivity));
        pulltofresh.setPullDownEnable(true);
        pulltofresh.setPullUpEnable(false);
        pulltofresh.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                pagenow = 1;
                query(pagenow);
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                MyselHelpOrder1Fragment.this.pagenow++;
                append(MyselHelpOrder1Fragment.this.pagenow);
            }
        });
        pulltofresh.autoRefresh();
    }

    public void  initPayDialog(final String money, final String orderId, final String fromuserId, final String touserId, final Integer position){
        paydialog=new Dialog(mActivity);
        paydialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        paydialog.setContentView(R.layout.dialog_rechargemoney);
        radioGroup=paydialog.findViewById(R.id.rg_pay);

        TextView recharage_title=paydialog.findViewById(R.id.recharage_title);
        recharage_title.setText("结算支付");
               EditText recharge_edit= paydialog.findViewById(R.id.recharge_edit);
        recharge_edit.setVisibility(View.GONE);
        View yuyue_left=paydialog.findViewById(R.id.yuyue_left);
        yuyue_left.setVisibility(View.VISIBLE);

        final RadioButton pay_moneypackage=paydialog.findViewById(R.id.pay_moneypackage);
        final RadioButton pay_paypackage=paydialog.findViewById(R.id.pay_paypackage);
        pay_moneypackage.setVisibility(View.VISIBLE);
        pay_moneypackage.setChecked(true);
        final RadioButton pay_wexin=paydialog.findViewById(R.id.pay_wexin);
        pay_wexin.setChecked(false);
        paydialog.findViewById(R.id.moneycount_rl);
        yuyue_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_moneypackage.setChecked(true);
            }
        });
        RelativeLayout wx_rl=paydialog.findViewById(R.id.wx_rl);
        wx_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_wexin.setChecked(true);
            }
        });
        RelativeLayout pay_rl=paydialog.findViewById(R.id.pay_rl);
        pay_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_paypackage.setChecked(true);
            }
        });


        Button paybt=paydialog.findViewById(R.id.paybt);

        paybt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("***********"+money+"*****"+"*********"+orderId);
                switch (radioGroup.getCheckedRadioButtonId()){
                    case R.id.pay_moneypackage:
                        myselfpayfor(money,fromuserId,touserId,orderId,position);
                        paydialog.dismiss();
                        break;
                    case R.id.pay_wexin:
                        Toast.makeText(mActivity.getApplicationContext(),"微信支付"
                                ,Toast.LENGTH_SHORT).show();
                        paydialog.dismiss();
                        break;
                    case R.id.pay_paypackage:
                        DecimalFormat decimalFormat=new DecimalFormat("0.00");
                        payV2(decimalFormat.format(Double.parseDouble(money)),"深圳复活生命科技有限公司-送宝","支付到其他账户上"+money+"元",orderId,touserId,position);
                        paydialog.dismiss();
                        break;
                }
            }
        });
        paydialog.show();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        if(rootView==null){
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            ButterKnife.bind(this, rootView);
            initData();
        }
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<HelpInfoDomain.DataBean> dataBeen;
        public LayoutInflater inflater;

        public RecylcerAdaper(List<HelpInfoDomain.DataBean> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.layout_user_needhelppayinfolistitem, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final IndexHoler ih = (IndexHoler) holder;
            final HelpInfoDomain.DataBean dataBean=dataBeen.get(position);
             ih.cir_icon.setImageResource(R.drawable.nim_avatar_default);
            Glide.with(MyselHelpOrder1Fragment.this)
                    .load(""+dataBean.getUserAvatarpath())
                    .asBitmap()
                    .placeholder(R.drawable.nim_avatar_default)
                    .centerCrop()
                    .animate(R.anim.fade_in)
                    .override(300,300)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            ih.cir_icon.setImageBitmap(resource);
                        }
                    });
             ih.uname.setText(dataBean.getUserName()+"");
             if(dataBean.getUserSex()==0){
                 ih.sex_rl.setBackgroundColor(getResources().getColor(R.color.default_blue));
                 ih.sex_iv.setImageResource(R.mipmap.sex_male_while);
             }else{
                 ih.sex_rl.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                 ih.sex_iv.setImageResource(R.mipmap.sex_female_while);
             }
             ih.sex_tv.setText(""+dataBean.getUserAge());
            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("id",dataBean.getUserId());
              //      Tools.redirectActivity(mActivity, UserPersonCenterActivity.class,map);
                }
            });
            ih.gofukuan_bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    List<User> userList= Xutils.queryAll(mActivity.getApplication(),User.class);
                    if(userList==null){
                        return;
                    }
                    User user=userList.get(0);
                     if(TextUtils.isEmpty(user.getUserPaypassword())){
                         Tools.redirectActivity(mActivity, ModifyPayPassActivity.class);
                    Toast.makeText(getActivity().getApplicationContext(),"请设置支付密码",Toast.LENGTH_SHORT).show();
                         return;
                     }
                    DecimalFormat decimalFormat=new DecimalFormat("0.00");
                    if(TextUtils.isEmpty(dataBean.getOrderMoney())){
                        return;
                    }
                    dialogPayDialog(decimalFormat.format(Double.parseDouble(dataBean.getOrderMoney()))+"",""+dataBean.getOrderId(),user.getUserId()+"",
                            dataBean.getUserId()+"",position);
                }
            });
        }
        public void dialogPayDialog(final String money, final String orderId, final String fromuserId, final String touserId,
                                    final int position){
              if(isFirstPay){
                  final Dialog    confirm_dialog=new Dialog(mActivity);
                  confirm_dialog.setContentView(R.layout.dialog_paymoney);
                  confirm_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                  final EditText confirm_edit_tv=confirm_dialog.findViewById(R.id.edit_tv);
                  TextView exitbt=confirm_dialog.findViewById(R.id.exitbt);
                  exitbt.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View view) {
                          confirm_dialog.dismiss();
                      }
                  });
                  TextView readby=confirm_dialog.findViewById(R.id.readby);
                  readby.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View view) {
                          if(TextUtils.isEmpty(confirm_edit_tv.getText().toString().trim())){
                              Toast.makeText(mActivity.getApplicationContext(),"支付密码不能为空",Toast.LENGTH_LONG).show();
                              return;
                          }
                          List<User> userList= Xutils.queryAll(mActivity.getApplication(),User.class);
                          if(userList==null){
                              return;
                          }
                          User user=userList.get(0);
                          if(TextUtils.equals(MD5Util.getMD5(confirm_edit_tv.getText().toString().trim()), user.getUserPaypassword())){
                              isFirstPay=false;
                              confirm_dialog.dismiss();
                              initPayDialog(money+"",orderId,fromuserId,touserId,position);
                          }else{
                              Toast.makeText(mActivity.getApplicationContext(),"支付密码输入错误",Toast.LENGTH_LONG).show();
                          }
                          System.out.println("*******************"+user.getUserPassword());
                      }
                  });
                  confirm_dialog.show();

              }else{
                  initPayDialog(money+"",orderId,fromuserId,touserId,position);
              }

        }


        public void initRefresh(List<HelpInfoDomain.DataBean> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }
        public void initAppend(List<HelpInfoDomain.DataBean> domains){
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }
        @Override
        public int getItemCount() {
            return dataBeen.size();
        }
        public void delete(int position){
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }
        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
            public CircleImageView cir_icon;
            public TextView uname;
            public Button gofukuan_bt;
            public RelativeLayout sex_rl;
            public ImageView sex_iv;
            public TextView sex_tv;
            public IndexHoler(View itemView) {
                super(itemView);
                rootView = itemView;
                uname = itemView.findViewById(R.id.uname);
                cir_icon = itemView.findViewById(R.id.cir_icon);
                gofukuan_bt=itemView.findViewById(R.id.gofukuan_bt);
                gofukuan_bt.setVisibility(View.VISIBLE);
                sex_rl=itemView.findViewById(R.id.sex_rl);
                sex_iv=itemView.findViewById(R.id.sex_iv);
                sex_tv=itemView.findViewById(R.id.sex_tv);
            }
        }


    }




    public void query(int pagenow){

        Map<String,String> map=new HashMap<>();
        map.put("pagenow",pagenow+"");
        map.put("helpId",mActivity.helpId+"");
        map.put("orderState","1");
        Xutils.POST(HttpUrl.userhelporderbyhelpid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                Gson gson=new Gson();
                HelpInfoDomain domain=gson.fromJson(result,HelpInfoDomain.class);
                switch (domain.getState()){
                    case HttpCode.SUCCESS:
                        if(domain.getData()!=null&&domain.getData().size()!=0){
                            if(adpter==null){
                                recyclerview.setAdapter(adpter=new RecylcerAdaper(domain.getData(),mActivity));
                            }else{
                                adpter.initRefresh(domain.getData());
                            }

                        }else{
                            if(adpter!=null){
                                List<HelpInfoDomain.DataBean> dataBeanList=new ArrayList<HelpInfoDomain.DataBean>();
                                adpter.initRefresh(dataBeanList);
                            }
                        }
                        break;
                    case HttpCode.ERROR:
                        if(adpter!=null){
                            List<HelpInfoDomain.DataBean> dataBeanList=new ArrayList<HelpInfoDomain.DataBean>();
                            adpter.initRefresh(dataBeanList);
                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void append(int pagenow){
        lastloading=true;
        Map<String,String> map=new HashMap<>();
        map.put("pagenow",pagenow+"");
        map.put("helpId",mActivity.helpId+"");
        map.put("orderState","1");
        Xutils.POST(HttpUrl.userhelporderbyhelpid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                lastloading=false;
                Gson gson=new Gson();
                HelpInfoDomain domain=gson.fromJson(result,HelpInfoDomain.class);
                switch (domain.getState()){
                    case HttpCode.SUCCESS:
                        if(domain.getData()!=null&&domain.getData().size()!=0){
                            if(adpter==null){
                                recyclerview.setAdapter(adpter=new RecylcerAdaper(domain.getData(), mActivity));

                            }else{
                                adpter.initAppend(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                lastloading=false;
                pulltofresh.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void payV2(final String total_account, String title, String content, final String orderId, final String touserId,final int position) {
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(HttpUrl.PAY_APPID,total_account,title,content, false);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String privateKey = HttpUrl.PAY_RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, false);
        final String orderInfo = orderParam + "&" + sign;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(mActivity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = HttpUrl.SDK_PAY_FLAG;
                msg.obj = result;
                Bundle bundle=new Bundle();
                bundle.putString("orderId",orderId);
                bundle.putString("touserId",touserId);
                bundle.putString("money",total_account);
                bundle.putInt("position",position);

                  msg.setData(bundle);
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    public  void myselfpayfor(String money,String fromuserId,String touserId,String orderId,final int position){
         if(ispayLoding){
             return;
         }
        ispayLoding=true;
        Map<String,String> map=new HashMap<String, String>();
        map.put("fromuserId",fromuserId);
        map.put("touserId",touserId);
        map.put("orderMoney",money);
        map.put("orderId",orderId);
        Xutils.POST(HttpUrl.userhelporderpayforuser, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ispayLoding=false;
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    Toast.makeText(getActivity().getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                   switch (jsonObject.getInt("state")){
                       case  HttpCode.SUCCESS:
                           if(adpter!=null){
                               adpter.delete(position);
                           }
                           pulltofresh.autoRefresh();
                           break;
                       case HttpCode.ERROR:

                           break;
                   }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ispayLoding=false;
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }



    public  void payfor(String orderId,String touserId,String money,final int position){
        if(ispayLoding){
            return;
        }
        ispayLoding=true;
        Map<String,String> map=new HashMap<String, String>();
        map.put("orderId",orderId);
        map.put("touserId",touserId);
        map.put("orderMoney",money);
        Xutils.POST(HttpUrl.userhelporderpayupdatestate, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ispayLoding=false;
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    Toast.makeText(getActivity().getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                    switch (jsonObject.getInt("state")){
                        case  HttpCode.SUCCESS:
                            if(adpter!=null){
                                adpter.delete(position);
                            }
                            pagenow=1;
                            query(pagenow);
                            mActivity.order2.pagenow=1;
                            mActivity.order2.query( mActivity.order2.pagenow);
                            break;
                        case HttpCode.ERROR:

                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ispayLoding=false;
                Toast.makeText(getActivity().getApplicationContext(),"请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
}
